package com.shuiyun.demo.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.shuiyun.demo.entity.JobPlanDemo01;
import com.shuiyun.demo.job.JobDemo01;
import com.shuiyun.demo.utils.ScheduleUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: qurtzDemo
 * @description:
 * @author: shuiyun
 * @create: 2020-09-24 10:44
 **/
@RestController
@RequestMapping("job")
@Slf4j
@Api(tags = "定时任务管理接口")
public class JobController {

    @Autowired
    private ScheduleUtils scheduleUtils;

    @GetMapping("/simpleJob")
    @ApiOperation("创建简单的定时任务")
    public String simpleJob(){
        // 创建执行计划
        Map<String,Object> params = new HashMap<>();
        params.put("name","lisi");
        JobPlanDemo01 plan = new JobPlanDemo01();
        plan.setExecuteTime(DateUtil.offsetSecond(new Date(),10));
        plan.setJobId(IdUtil.simpleUUID());
        plan.setJobParams(params);
        scheduleUtils.createOnceScheduleJob(plan, JobDemo01.class);
        return "ok";
    }

    @GetMapping("/cronJob")
    @ApiOperation("创建cron定时任务")
    public String cronJob(String name,String cron){
        String jobId = IdUtil.simpleUUID();
        // 创建执行计划
        Map<String,Object> params = new HashMap<>();
        params.put("name",name);
        JobPlanDemo01 plan = new JobPlanDemo01();
        plan.setJobId(jobId);
        plan.setJobParams(params);
        plan.setJobCron(cron);
        scheduleUtils.createScheduleJob(plan, JobDemo01.class);
        return jobId;
    }

    @GetMapping("/pauseJob")
    @ApiOperation("暂停定时任务")
    public String pauseJob(String jobId){
        scheduleUtils.pauseJob(jobId);
        log.info("暂停定时任务成功");
        return "pause success";
    }

    @GetMapping("/resumeJob")
    @ApiOperation("恢复定时任务")
    public String resumeJob(String jobId){
        scheduleUtils.resumeJob(jobId);
        log.info("恢复定时任务成功");
        return "resume success";
    }

    @GetMapping("/deleteJob")
    @ApiOperation("删除定时任务")
    public String deleteScheduleJob(String jobId){
        scheduleUtils.deleteScheduleJob(jobId);
        log.info("删除定时任务成功");
        return "delete success";
    }

}
